package com.cnpc.netty.transfer;

import java.util.concurrent.TimeUnit;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.EventLoop;

/**
 * 负责监听运行时连接断开（例如：断网、服务端关闭等等）,进行重新链接
 *
 */
public class ClientPoHandlerProto extends ChannelInboundHandlerAdapter {
	private TcpConnection imConnection = new TcpConnection();
	/*
	 * @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { //
	 * MessageProto.Message message = (MessageProto.Message) msg; //
	 * System.out.println("client:" + message.getContent()); }
	 */

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		cause.printStackTrace();
		ctx.close();
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		System.err.println("掉线了...");
		// 使用过程中断线重连
		final EventLoop eventLoop = ctx.channel().eventLoop();
		eventLoop.schedule(new Runnable() {
			@Override
			public void run() {
				imConnection.connect(Transfer.tcpip, Transfer.tcpport);
			}
		}, 1L, TimeUnit.SECONDS);
		super.channelInactive(ctx);
	}

}